const connectionPoll = require("../app/mysql");
const {momentList,momentSearchById,momentUpdate,momentRemove} = require('../services/moment.service')

class momentController
{
    //创建评论
    async create(ctx,next)
    {
        //得到数据
       
        const { name,id } = ctx.user;
        const content = ctx.request.body.content;
        console.log("user:", ctx.user, "content:", ctx.request.body.content);
        try {
        //保存数据
        const statement = "insert into t_moment(user_id,name,content) values(?,?,?)";
        const [val] = await connectionPoll.promise().execute(statement, [id, name, content]);
            //返回插入成功的消息
            ctx.body = {
                content: content,
                proofile: {
                    user: name,
                    user_id:id
                }
            }
        }
        catch(err)
       {
            return ctx.body = err;
       }
       await next();
    }

    //创建一个查找的服务
    async list(ctx, next)
    {
        //获取query数据
        const { limit, offset } = ctx.query;
        let result = await momentList(offset, limit);
        
        //自己处理一遍在进行返回
        result = result.map((val, index) => {
            return {
                name: val.name,
                id: val.user_id,
                data: {
                    content:val.content
                }
            }
        })

        ctx.body = result;
        await next();
    }

    async searchById(ctx, next)
    {
        const { id } = ctx.params;
        console.log("id:", id);
        const result = await momentSearchById(id);
        if (!result) 
        {
            return ctx.body = {
               message:"没有数据"
           }    
        }

        ctx.body = {
            message: "查询成功",
            content: result.content
        }
        await next();
    }
    
    async update(ctx, next)
    {
        const { content } = ctx.request.body;
        const { id } = ctx.params;
        //进行修改
        const result = momentUpdate(content, id);  
        if (!result)
        {
            return ctx.body = {
               message:"修改失败"
           }    
        }

        ctx.body = {
            message: "修改成功",
            content:content
        }

        await next();
    }

    async remove(ctx, next)
    {
        //获取id
        const { id } = ctx.params;
        //进行删除操作
        const result = momentRemove(id);
        if (!result)
        {
            return ctx.body = {
               message:"删除失败"
           }    
        }

        ctx.body = {
            message:"删除成功"
        }

        await next();
    }
}

module.exports = new momentController();